package main

import (
	"bytes"
	"fmt"
	"io"
	"net"
	"runtime"
	"sync"
	"time"
)

// Server 服务端
type Server struct {
	Ip   string
	Port int
	//广播消息的Channel
	Message chan string

	//存放在线用户
	OnlineMap map[string]*User
	//对OnlineMap操作的锁
	mapLock sync.RWMutex
}

// NewServer 创建一个server对象
func NewServer(Ip string, Port int) *Server {
	server := &Server{
		Ip:        Ip,
		Port:      Port,
		Message:   make(chan string),
		OnlineMap: make(map[string]*User),
		//mapLock:   sync.RWMutex{},
	}
	return server
}

// Start 启动Server服务
func (server *Server) Start() {
	//socket listen
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", server.Ip, server.Port))
	if err != nil {
		fmt.Println("net.Listen err:", err)
		return
	}
	//close socket listen
	defer func(listener net.Listener) {
		err := listener.Close()
		if err != nil {
			fmt.Println("close net.Listener error:", err)
		}
	}(listener)

	//监听广播消息channel
	go server.ListenMessager()
	//accept
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("listener accept err:", err)
			continue
		}
		//do handler
		go server.Handler(conn)
	}

}

func (server *Server) Handler(conn net.Conn) {
	//将当前用户加入OnlineMap中
	user := NewUser(conn, server)

	//上线
	user.Online()

	//监听用户是否存活的chan
	isLive := make(chan bool)

	//接收客户端发送的消息
	//对conn 连接进行读取
	go func() {
		buf := make([]byte, 4096)
		for {
			//重置下线时间
			time.After(time.Second * 100)
			n, err := conn.Read(buf)
			if n == 0 {
				//下线
				user.Offline()
				return
			}
			if err != nil && err != io.EOF {
				fmt.Println("Conn Read err:", err)
			}

			//提取用户消息
			msg := string(buf[:n-1])
			fmt.Println("用户消息:", msg)
			user.DoMessage(msg)

			//用户续活
			isLive <- true
		}

	}()

	//当前handle阻塞
	for {
		select {
		//用户存活 重置定时器
		case <-isLive:
			// 当前用户活跃的，重置定时器
			//不做任何事情，为了激活select，更新下面的定时器

		//此时表示用户需要自动下线
		case <-time.After(time.Second * 100):
			//退出当前Handel
			server.mapLock.Lock()
			delete(server.OnlineMap, user.Name)
			server.mapLock.Unlock()
			user.SendMsg("您太久未操作，已被踢下线")
			close(user.C)
			conn.Close()
			runtime.Goexit() //结束当前goroutine
		}
	}

}

// ListenMessager 监听广播消息的Channel
func (server *Server) ListenMessager() {
	for {
		msg := <-server.Message
		server.mapLock.Lock()
		for _, user := range server.OnlineMap {
			user.C <- msg
		}
		server.mapLock.Unlock()
	}
}

// BroadCast 广播消息
func (server *Server) BroadCast(user *User, msg string) {
	var by bytes.Buffer
	by.WriteString("广播消息")
	by.WriteString("[")
	by.WriteString(user.Addr)
	by.WriteString("]")
	by.WriteString(user.Name)
	by.WriteString(":")
	by.WriteString(msg)
	by.WriteString("\n")

	s := by.String()
	fmt.Println(s)
	server.Message <- s
}
